package com.itstyle.es.service.impl;

import cn.hutool.core.convert.Convert;
import com.itstyle.es.common.constant.PageConstant;
import com.itstyle.es.common.model.Pages;
import com.itstyle.es.entity.SysLogs;
import com.itstyle.es.repository.ElasticLogRepository;
import com.itstyle.es.service.LogService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.index.query.GeoBoundingBoxQueryBuilder;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.stereotype.Component;
import org.zxp.esclientrhl.repository.*;

import javax.annotation.Resource;
import java.util.List;

@Component
@Slf4j
public class LogServiceImpl implements LogService {

    @Resource
    private ElasticLogRepository<SysLogs, Long> elasticLogRepository;

    //使用方法与ElasticsearchTemplate大同小异，只有一些比较基础的方法，去掉了Clazz类类型的入参
    @Resource
    ElasticsearchTemplate<SysLogs, Long> elasticsearchTemplate;

    @SneakyThrows
    @Override
    public void saveLog(SysLogs log) {
        elasticLogRepository.save(log);

        //    可以定制routing路由字段来指定数据被索引到哪个分片上
        //    elasticsearchTemplate.save(main2, "R01");
    }

    @Override
    public Pages<SysLogs> searchLogPage(Integer pageNumber, Integer pageSize, Integer platFrom,
                                        String searchContent) {
        // 校验分页参数
        if (pageSize == null || pageSize <= 0) {
            pageSize = PageConstant.PAGE_SIZE;
        }

        if (pageNumber == null || pageNumber < PageConstant.DEFAULT_PAGE_NUMBER) {
            pageNumber = PageConstant.DEFAULT_PAGE_NUMBER;
        } else {
            pageNumber = pageNumber - 1;
        }

        // 构建搜索查询
        // searchRequest是官方原生查询输入，此方法在工具无法满足需求时使用

        //支持sql
        //支持uri query string的查询


        //（全查询）
        // List<SysLogs> main2List = elasticsearchTemplate.search(new MatchAllQueryBuilder(), SysLogs.class);
        //
        // //最多返回6条数据
        // List<SysLogs> main3List = elasticLogRepository.searchMore(new MatchAllQueryBuilder(), 6);

        //支持分页、高亮、排序、查询条件的定制查询
        //分页
        PageSortHighLight psh = new PageSortHighLight(pageNumber, pageSize);
        //排序字段，注意如果proposal_no是text类型会默认带有keyword性质，需要拼接.keyword
        String sorter = "time.keyword";
        Sort.Order order = new Sort.Order(SortOrder.ASC, sorter);
        psh.setSort(new Sort(order));
        //定制高亮，如果定制了高亮，返回结果会自动替换字段值为高亮内容
        psh.setHighLight(new HighLight().field("username"));
        //可以单独定义高亮的格式
        //new HighLight().setPreTag("<em>");
        //new HighLight().setPostTag("</em>");
        PageList<SysLogs> pageList = new PageList<>();

        QueryBuilder queryBuilder = QueryBuilders.matchPhraseQuery("username",searchContent);
        try {
            pageList = elasticLogRepository.search(queryBuilder, psh);
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new RuntimeException(e);
        }


        // QueryBuilder qb = QueryBuilders.termQuery("name", "zhang");


        Pages<SysLogs> pages = new Pages<SysLogs>();
        pages.setRows(pageList.getList());
        pages.setTotal(Convert.toInt(pageList.getTotalElements()));
        pages.setTotalPages(pageList.getTotalPages());
        return pages;
    }

    // public void searchGeo() {
    //     GeoPoint topLeft = new GeoPoint(32.030249, 118.789703);
    //     GeoPoint bottomRight = new GeoPoint(32.024341, 118.802171);
    //     GeoBoundingBoxQueryBuilder geoBoundingBoxQueryBuilder =
    //             QueryBuilders.geoBoundingBoxQuery("geo")
    //                     .setCorners(topLeft, bottomRight);
    //     // elasticsearchTemplate.search(geoBoundingBoxQueryBuilder, GeoPojo.class);
    // }
}
